from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from .models import Article
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
import json
from openai import OpenAI

@require_http_methods(["GET"])
def get_article_list(request):
    try:
        # 获取查询参数
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 10))
        search = request.GET.get('search', '')

        # 构建查询条件
        queryset = Article.objects.all().order_by('-created_at')

        if search:
            queryset = queryset.filter(
                Q(title__icontains=search) |
                Q(content__icontains=search)
            )

        # 分页处理
        paginator = Paginator(queryset, size)
        page_obj = paginator.get_page(page)

        # 构建返回数据
        articles = []
        for item in page_obj.object_list:
            articles.append({
                'id': item.id,
                'title': item.title,
                'content': item.content,
                'type': item.type,
                'created_at': item.created_at.strftime('%Y-%m-%d %H:%M'),
                'author': item.author.username if item.author else None,
                'views': item.views
            })

        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': {
                'items': articles,
                'total': paginator.count,
                'page': page,
                'size': size
            }
        })

    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })


@csrf_exempt
@login_required
def create_article(request):
    try:
        if request.method != 'POST':
            return JsonResponse({
                'code': 405,
                'message': 'Method not allowed',
                'data': None
            })

        data = json.loads(request.body)
        
        article = Article.objects.create(
            type=data.get('type'),
            title=data.get('title'),
            content=data.get('content'),
            author=request.user
        )

        return JsonResponse({
            'code': 200,
            'message': '创建成功',
            'data': {
                'id': article.id,
                'type': article.type,
                'title': article.title,
                'created_at': article.created_at.strftime('%Y-%m-%d %H:%M')
            }
        })

    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'创建失败: {str(e)}',
            'data': None
        })

def delete_article(request, article_id):
    try:
        # 获取要删除的文章
        article = Article.objects.get(id=article_id)
        
        # 检查权限：只有管理员或文章作者可以删除
        if not (request.user.role == 'admin' or request.user == article.author):
            return JsonResponse({
                'code': 403,
                'message': '无权删除此文章',
                'data': None
            })
        
        # 执行删除
        article.delete()
        
        return JsonResponse({
            'code': 200,
            'message': '删除成功',
            'data': None
        })
        
    except Article.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'message': '文章不存在',
            'data': None
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'删除失败: {str(e)}',
            'data': None
        })

@require_http_methods(["POST"])
def ai_chat(request):
    try:
        # 获取前端传递的查询内容
        data = json.loads(request.body)
        query = data.get('query', '')
        from PEEIEPService import settings
        
        client = OpenAI(
            base_url="https://ark.cn-beijing.volces.com/api/v3",
            api_key=settings.ARK_API_KEY,
            timeout=120    
        )

        completion = client.chat.completions.create(
            # 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
            model="doubao-1-5-pro-32k-250115",
            messages=[
                {"role": "system", "content": "你是人工智能助手"},
                {"role": "user", "content": query},
            ],
        )
        print(completion.choices[0].message.content)
        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': {
                'content': completion.choices[0].message.content
            }
        })

    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })